package com.starsoft.smdc.crawler.netease;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.starsoft.frame.fileimport.CsvReader;
import com.starsoft.frame.fileimport.pojo.Column;
import com.starsoft.frame.fileimport.pojo.DataTable;
import com.starsoft.frame.fileimport.pojo.NullType;
import com.starsoft.frame.fileimport.pojo.Table;
import com.starsoft.frame.fileimport.pojo.Table.TitleType;
import com.starsoft.frame.fileimport.pojo.ValueType;
import com.starsoft.frame.util.DateUtil;
import com.starsoft.frame.util.MapUtil;
import com.starsoft.smdc.bean.SmdcMarketDaily;
import com.starsoft.smdc.bean.SmdcMarketDailyId;
import com.starsoft.smdc.bean.SmdcSecurity;
import com.starsoft.smdc.crawler.common.MarketDailyCrawler;
import com.starsoft.smdc.service.HolidayService;

public class MarketDailyNetease extends NeteaseService implements MarketDailyCrawler{
	
	private static Logger logger = LoggerFactory.getLogger(MarketDailyNetease.class);
	
	@Autowired
	private HolidayService holidayService;
	
	@Override
	public List<SmdcMarketDaily> update(SmdcSecurity security, Date begin) {
		return update(Arrays.asList(security), Arrays.asList(begin));
	}
	
	@Override
	public List<SmdcMarketDaily> update(List<SmdcSecurity> securityList,
			List<Date> begin) {
		Date endDate = this.getEndDate();
		List<SmdcMarketDaily> result = new ArrayList<SmdcMarketDaily>();

		for (int i=0;i< securityList.size();i++) {
			if(begin.get(i).after(DateUtil.ceilTime(endDate))){
				continue;
			}
			SmdcSecurity security = securityList.get(i);
			if(!DateUtil.isToday(begin.get(i))){
				result.addAll(updateHistory(security, begin.get(i), endDate));
			}
		}
		marketDailyDao.saveOrUpdateBatch(result);
		return result;
	}	
	
	private Date getEndDate(){
		Date end = new Date();
		if(holidayService.isBeforeClose(end)){
			end = holidayService.getNextBusinessDay(end, -1);
		} else {
			end = holidayService.getBusinessDay(end, true);
		}
		return end;
	}
	
	private List<SmdcMarketDaily> updateHistory(SmdcSecurity security, Date begin, Date end) {
		List<SmdcMarketDaily> marketList = new ArrayList<SmdcMarketDaily>();
		begin = DateUtil.floorTime(begin);
		if(end.before(begin)){
			return marketList;
		}
		
		String apiName = "market";
		String[] params = { convertSecId(security.getSecId(), false), DateUtil.toString(begin, "yyyyMMdd"),
				DateUtil.toString(end, "yyyyMMdd") };
		InputStream response = this.downLoad(apiName, params);
		
		List<Column> columnList = new ArrayList<Column>();
		columnList.add(new Column("股票代码", "ticker", ValueType.String, NullType.notnull));
		columnList.add(new Column("日期", "tradeDate", ValueType.Date, NullType.notnull, "yyyy-MM-dd"));
		columnList.add(new Column("前收盘", "preClosePrice", ValueType.Double, NullType.notnull));
		columnList.add(new Column("开盘价", "openPrice", ValueType.Double, NullType.nullable));
		columnList.add(new Column("收盘价", "closePrice", ValueType.Double, NullType.notnull));
		columnList.add(new Column("最高价", "highPrice", ValueType.Double, NullType.nullable));
		columnList.add(new Column("最低价", "lowPrice", ValueType.Double, NullType.nullable));
		columnList.add(new Column("成交金额", "turnoverValue", ValueType.Double, NullType.nullable));
		columnList.add(new Column("成交量", "turnoverVol", ValueType.Double, NullType.nullable));
		columnList.add(new Column("换手率", "turnoverRate", ValueType.Double, NullType.nullable));
		Table table = new Table(TitleType.OnlyCode, columnList);
		
		CsvReader reader = new CsvReader();
		DataTable dataTable = reader.read(response, table);
		
		for (Map<String, Object> mapObject : dataTable.getData()) {
			SmdcMarketDailyId id = new SmdcMarketDailyId(security.getSecId(), (Date) mapObject.get("tradeDate"));
			SmdcMarketDaily marketDaily = marketDailyDao.get(id);
			if(marketDaily==null){
				marketDaily = new SmdcMarketDaily(id);
			}
			MapUtil.updateBean(marketDaily, mapObject);
			if(marketDaily.getIsOpen()==null){
				if (marketDaily.getTurnoverVol() == 0) {
					marketDaily.setIsOpen(false);
				} else {
					marketDaily.setIsOpen(true);
				}
			}
			double priceChange = marketDaily.getClosePrice()-marketDaily.getPreClosePrice();
			marketDaily.setPriceChange(priceChange);
			marketDaily.setPercent(priceChange/marketDaily.getPreClosePrice());
			marketList.add(marketDaily);
		}
		return marketList;
	}
	
}
